package logic

import (
	"context"
	"fmt"
	"yuni/model/cache"
	"yuni/model/mysql"

	"yuni/yunirpc/internal/svc"
	"yuni/yunirpc/yunirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *yunirpc.LoginRequest) (*yunirpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.Account).Result()
	if in.SengSms != result {
		return nil, fmt.Errorf("短信验证码输入错误")
	}

	var user mysql.User
	mysql.Db.Debug().Where("account=?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("账号不存在,请前去注册")
	}
	m := mysql.User{
		Account:  in.Account,
		Password: in.Password,
	}
	mysql.Db.Debug().Find(&m)
	return &yunirpc.LoginResponse{
		UserId: int64(m.ID),
	}, nil
}
